package finanz.kontrolle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import classes.ArrayGenerico;
import classes.Funcoes;
import classes.ListAdapterGenerico;
import classes.Parametros;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;

public class BancoActivity extends MenuActivity implements OnClickListener {
	
	private Parametros par = Parametros.getInstance();
	
	public void onCreate( Bundle bundle ) {
		super.onCreate( bundle );
		setContentView( R.layout.banco );

		this.listarBancos();
	}
	
	public void onClick( View arg0 ) {}
	
	private void listarBancos() {
		String strUrl = par.getUrl().toString() + getResources().getString( R.string.urlBancoListar );
		
		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost( strUrl );
	    
	    try {
	        List<NameValuePair> BancoValuePairs = new ArrayList<NameValuePair>(1);
	        BancoValuePairs.add(new BasicNameValuePair("DatabaseID", par.getDatabase()));
	        httppost.setEntity(new UrlEncodedFormEntity(BancoValuePairs));

	        HttpResponse response = httpclient.execute(httppost);

	        Funcoes f = new Funcoes();
	        StringBuilder retorno = f.inputStreamToString( response.getEntity().getContent() );

	        try {
				
				JSONObject jo = new JSONObject( retorno.toString() );
				JSONArray arrayBanco = jo.getJSONArray( "banco" );
				
				ArrayGenerico[] bancos = new ArrayGenerico[ arrayBanco.length() ];
				
				for ( int b = 0; b < bancos.length; b++ ) {
					JSONObject banco = new JSONObject( arrayBanco.getJSONObject( b ).toString() );
					
					bancos[ b ] = new ArrayGenerico();
					bancos[ b ].setID( banco.getString( "BancoID" ) );
					bancos[ b ].setLabel( banco.getString( "Nome" ) );
				}
				
				ListView lv = ( ListView ) findViewById( R.id.lvBanco );
				lv.setAdapter( new ListAdapterGenerico( this, BancoCadastroActivity.class, bancos, "BancoID", "Novo Banco" ) );
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
	        
	    } catch (ClientProtocolException e) {
	    	e.printStackTrace();
	    } catch (IOException e) {
	    	e.printStackTrace();
	    }
	}

}